using System;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Threading;
using NUnit.Framework;
using Universe.Farm.RemotingService;

namespace Universe.Farm.Tests
{
    [TestFixture]
    public class TestViaRemoting
    {

        private Service.Farm _farm = null;
        private ConfigurationContainer _config;
        private RemotingFarmService _serviceImpl;

        [TestFixtureSetUp]
        public void Start_Farm_Node_And_Publish_On_NamedPipe()
        {
            _config = MyEnvironment.CreateConfiguration(TimeSpan.FromSeconds(100));
            _farm = new Service.Farm(_config);
            _farm.Start();
            _serviceImpl = new RemotingFarmService(_config);
            IpcServerChannel channel = new IpcServerChannel("serverfarm");
            ChannelServices.RegisterChannel(channel, true);
            RemotingServices.Marshal(_serviceImpl, "service.rem");
        }

        [Test]
        public void Connect_Lookup_Get()
        {
            IFarmService service = _serviceImpl;
            IpcClientChannel channel = new IpcClientChannel();
            ChannelServices.RegisterChannel(channel, true);
            service = (IFarmService) Activator.GetObject(typeof (IFarmService), "ipc://serverfarm/service.rem");
            
            ServicesScope waitScope = 
                ServicesScope.Empty
                .Add(Environment.MachineName, "ComputerInfo")
                .Add(Environment.MachineName, "LocalSqlServer");

            MyEnvironment.Wait(service, waitScope, TimeSpan.FromSeconds(5));

            IList<HealthInfo> allFound = service.GetServices(ServicesScope.FullScope);
            Assert.GreaterOrEqual(allFound.Count, 2, "2 service health is available");

            ServicesScope localComputerInfoScope = ServicesScope.Empty.Add(Environment.MachineName, "ComputerInfo");
            IList<HealthInfo> myServices = service.GetServices(localComputerInfoScope);
            HealthInfo healthInfo = myServices.Count == 0 ? null : myServices[0];
            Assert.IsNotNull(healthInfo, "there is a computer info");

        }

        [TestFixtureTearDown]
        public void TearDown()
        {
            _farm.Stop();
        }

    }
}
